<?php
/**
 *  💡 免责声明：本软件不得用于商业用途，仅做学习交流
 *  ⚠️ 权利声明：本软件由版权人提供产品技术支持
 *  📅 项目编号：NX2025-0135
 */
namespace App\Providers;

use App\Models\User;
use Closure;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class CheckTokenMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        if ($request->hasHeader('token')) {
            try {
                $usertoken = decrypt($request->header('token'));
                $request->USER_ID = $usertoken['id'];
                $uid = $usertoken['id'];
                $user = User::query()->find($uid);
                if (! $user) {
                    return responses('签名错误', 104);
                }

                if ($user->status == 0) {
                    return responses('该账户已被冻结！如有需要请联系相关工作人员', 2015);
                }
                if (env('OPEN_TOKEN_EXPIRED', false)) {
                    $key = "user_ttl:{$uid}";
                    if (Cache::has($key)) {
                        Cache::put($key, true, now()->addMinutes(env('EXPIRED_MINUTE', 30)));
                        return $next($request);
                    }
                    return responses('令牌过期', 3);
                }
//                if(!isset($usertoken['session_key'])){
//                    return res('INVALID TOKEN EXPIRED',101);
//                }
//                $request->SESSION_KEY =  $usertoken['session_key'];
                return $next($request);
            } catch (Exception $exception) {
                return responses('无效的令牌', 101);
            }
        } else {
            return responses('无访问权限', 200);
        }
    }
}
